import {get, post} from '~/business/NetRequest'

export const dataBus = {
  markets: {
    baseCoins: [],
    coinsArr: [],
    coinPrices: undefined,
    refPrices: {},
    markedPairs: [],
  },
  orders: {
    opened: [],
    closed: []
  },
  wallet: {
    btcValuation: 0,
    usdValuation: 0,
    quoteSymbols: [],
    balances: {}
  },
  orderListeners: [],
  addOrder(para) {
    para.timestamp = Date.now()
    para.status = 'opened'
    this.orders.opened.push(para)
    this.orderListeners.forEach(item => {
      item.onOrdersChange()
    })
  },
  cancelOrder(orderId, listener) {
    get({
      api: 'ExchangeOrder/' + orderId,
      isDelete: true,
      success: listener.onSuccess,
      error: listener.onError
    })
  },
  loadCoins(onSuccess) {
    const self = this
    get({
      api: 'MarketInfo/coins',
      success: (data) => {
          self.markets.baseCoins = data.map(item => item.quoteCoin)
          self.markets.baseCoins.push('Marked')
          self.markets.coinsArr = data.map(item => item.baseCoins)
          onSuccess && onSuccess(self.markets)
      }
    })
  },
  loadCoinPrices(onSuccess) {
    const self = this
    get({
      api: 'MarketInfo/prices',
      success: data => {
        let prices = {}
        data.prices.forEach(item => {
          prices[item.coinSymbol] = item
        })
        self.markets.coinPrices = prices
        self.markets.refPrices = data.zeroTimePricesOfToday
        onSuccess && onSuccess(self.markets)
      }
    })
  },
  loadMarks(onSuccess) {
    const self = this
    get({
      api: 'MarketInfo/marks',
      success: data => {
        let pairs = []
        data.coinIds && data.coinIds.forEach(item => {
          let newItem = `${item.baseCoin.replace('EXC_', '')}/${item.quoteCoin.replace('EXC_', '')}`
          pairs.push(newItem)
        })
        self.markets.markedPairs = pairs
        onSuccess && onSuccess(self.markets)
      }
    })
  },
  markPair(pair) {
    let coinId = pair.split('/')[0]
    let quoteCoinId = pair.split('/')[1]
    if (this.markets.markedPairs.indexOf(pair) >= 0) {
      this.markets.markedPairs.pop(pair)
    } else {
      this.markets.markedPairs.push(pair)
    }
    post({
      api: 'MarketInfo/mark',
      data: {
        coinId,
        quoteCoinId
      }
    })
  },
  isMarked(pair) {
    return this.markets.markedPairs.indexOf(pair) >= 0
  },
  topGainers() {
    let baseCoins = this.markets.baseCoins,
      coinsArr = this.markets.coinsArr
    if (baseCoins.length == 0 || 
      coinsArr == undefined || 
      this.markets.coinPrices == undefined) {
      return []
    }
    let max=-1000, maxer=-1000, maxest=-1000
    let pair1, pair2, pair3
    for(let i=0; i<baseCoins.length; i++) {
      let base = baseCoins[i]
      if (base == 'Marked') {
        break
      }
      let coins = coinsArr[i]
      coins.forEach(item => {
        let coin = item.symbol
        let pair = `${coin}/${base}`
        let incre = this.calIncrement(coin, base)
        if (incre > maxest) {
          maxest = incre
          pair1 = pair
        } else if (incre > maxer) {
          maxer = incre
          pair2 = pair
        } else if (incre > max) {
          max = incre
          pair3 = pair
        }
      })
    }
    let ret = []
    let pairs = [pair1, pair2, pair3]
    pairs.forEach(item => {
      ret.push(this.constructDisplayItem(item.split('/')[0], item.split('/')[1]))
    })
    return ret
  },

  calIncrement(coin, base) {
    let priceInfo = this.markets.coinPrices[coin]
    let basePriceInfo = this.markets.coinPrices[base]
    let currentRatio = priceInfo.usdPrice/basePriceInfo.usdPrice
    let refRatio = this.markets.refPrices[coin]/this.markets.refPrices[base]
    let incre = (currentRatio-refRatio)/refRatio*100
    return incre
  },

  constructDisplayItem(coin, base) {
    let priceInfo = this.markets.coinPrices[coin]
    let incre = this.calIncrement(coin, base)
    let newItem = {}
    newItem.title = coin + '/' + base
    newItem.alt = '24H Vol ' + priceInfo.volumeIn24H
    newItem.title2 = (priceInfo.usdPrice/this.markets.coinPrices[base].usdPrice).toFixed(8)
    newItem.alt2 = '$' + priceInfo.usdPrice
    newItem.btn =  (incre > 0 ? '+' : '') + incre.toFixed(2) + '%'
    return newItem
  },
  orderListener(listener) {
    if (this.orderListeners.indexOf(listener) >= 0) {
      this.orderListeners.pop(listener)
    } else {
      this.orderListeners.push(listener)
    }
  },
  loadWallet(listener) {
    let self = this
    get({
      api: 'Wallet/summary',
      success: (ret) => {
        self.wallet = ret
        listener.onSuccess(ret)
      }
    })
  },
  loadLatestExchange(baseCoinId, quoteCoinId, listener) {
    get({
      api: `ExchangeOrder/latest?baseCoinId=${baseCoinId}&quoteCoinId=${quoteCoinId}`,
      success: (ret) => {
        listener.onSuccess(ret)
      }
    })
  },
  createOrder(isLimit, config, listener) {
    post({
      api: isLimit? 'ExchangeOrder/limit' : 'ExchangeOrder/market',
      data: config,
      success:listener.onSuccess,
      error:listener.onError
    })
  },
  loadMarketHistory(pair, listener) {
    let coin = pair.split('/')[0],
      quoteCoin = pair.split('/')[1]
    get({
      api: `MarketInfo/latest/24h?coin=${coin}&quoteCoin=${quoteCoin}`,
      success: listener.onSuccess,
      error:listener.onError
    })
  },

  loadLatestMarketHistory(coin, quoteCoin, lastTimeStamp, listener) {
    get({
      api: `MarketInfo/history?coin=${coin}&quoteCoin=${quoteCoin}&type=1&since=${lastTimeStamp}`,
      success: listener.onSuccess,
      error:listener.onError
    })
  },

  isExchangePassExist(listener) {
    get({
      api: 'account/exist',
      success: listener.onSuccess,
      error: listener.onError
    })
  },
  setFundPassword(oldPass, password, listener) {
    post({
      api: 'account/pay/changePwd',
      data: {
        oldPwd: oldPass,
        newPwd: password
      },
      success: listener.onSuccess,
      error: listener.onError,
    })
  },
  checkFundPassword(pass, listener) {
    post({
      api: 'account/pay/pwd',
      data: {
        password: pass
      },
      success: listener.onSuccess,
      error: listener.onError
    })
  },
  loadWalletDetail(listener) {
    const self = this
    get({
      api: 'Wallet',
      success: (ret) => {
        self.wallet.quoteSymbols = ret.quoteSymbols
        let balances = {}
        ret.balances.forEach(item => {
          balances[item.coinSymbol] = item
        })
        self.wallet.balances = balances
        listener.onSuccess && listener.onSuccess(ret)
      },
      error: listener.onError
    })
  },
  loadWalletCoin(coin, listener) {
    get({
      api: 'Wallet/' + coin,
      success: listener.onSuccess,
      error: listener.onError
    })
  },
  withDraw(config, listener) {
    post({
      api: 'Wallet/withdraw',
      data: config,
      success: listener.onSuccess,
      error: listener.onError
    })
  },
  loadOrders(quoteCoinId, baseCoinId, isBuy, listener) {
    get({
      api: `ExchangeOrder/open/${baseCoinId}/${quoteCoinId}/${(isBuy? 'buy' : 'sell')}`,
      error: listener.onError,
      success: listener.onSuccess
    })
  },
  loadCurrency(listener) {
    get({
      api: 'Currency',
      error: listener.onError,
      success: listener.onSuccess
    })
  },
  setProfile(currency, listener) {
    post({
      api: 'account/profile',
      data: {currency},
      error: listener.onError,
      success: listener.onSuccess
    })
  },
  loadAllOpenOrders(listener) {
    get({
      api: 'ExchangeOrder/open',
      error: listener.onError,
      success: listener.onSuccess,
    })
  },
  loadHistoryOrders(lastTimeStamp, listener) {
    get({
      api: 'ExchangeOrder/history?since=' + lastTimeStamp,
      error: listener.onError,
      success: listener.onSuccess,
    })
  },
  changeLoginPassword(oldPwd, newPwd, listener) {
    post({
      api: 'account/login/changePwd',
      data: {oldPwd, newPwd},
      success: listener.onSuccess,
      error: listener.onError
    })
  },
  loadHistoryTransaction(type, listener) {
    get({
      api: 'Wallet/history/' + type,
      success: listener.onSuccess,
      error: listener.onError
    })
  }
  
}